package com.sicnu.cheer.leaugebar.contacts.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.sicnu.cheer.generalmodule.adapter.base.CommonAdapter;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.fragment.base.BaseFragment;
import com.sicnu.cheer.generalmodule.util.Pinyin4JUtil;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.contacts.R;
import com.sicnu.cheer.leaugebar.contacts.activity.UserInfoActivity;
import com.sicnu.cheer.leaugebar.contacts.adapter.SortAdapter;
import com.sicnu.cheer.leaugebar.contacts.utils.PinyinComparator;
import com.sicnu.cheer.leaugebar.contacts.utils.SideBar;
import com.sicnu.cheer.leaugebar.contacts.utils.SortModel;
import com.sicnu.cheer.leaugebar.contacts.wigets.ClearEditText;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by cheer on 2017/3/3.
 * 所有的联系人界面
 */

public class AllContactsFragment extends BaseFragment {
    private PinyinComparator pinyinComparator;//拼音比较器
    private SideBar sideBar;//滑动实现快速查找
    private TextView dialog;
    private SortAdapter adapter;
    private ListView sortListView;
    private ClearEditText mClearEditText;
    private List<SortModel> sourceDataList;
    private ProgressDialog loadingDialog;
    @Override
    protected int setLayoutResourceId() {
        return R.layout.fragment_all_contacts;
    }

    @Override
    protected void initView() {
        super.initView();
        //实例化汉字转拼音类
        pinyinComparator = new PinyinComparator();
        sideBar = findViewById(R.id.fr_sidrbar);
        dialog = findViewById(R.id.fr_dialog);
        sideBar.setTextView(dialog);
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                if (adapter != null) {
                    int position = adapter.getPositionForSection(s.charAt(0));
                    if (position != -1) {
                        sortListView.setSelection(position);
                    }
                }
            }
        });

        sortListView = findViewById(R.id.sort_listview);
        //API21以上才有效果----第二种方式，比较简便
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            sortListView.setNestedScrollingEnabled(true);
        }
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                SortModel element = (SortModel) adapter.getItem(position);
                Intent intent = new Intent(mActivity, UserInfoActivity.class);
                intent.putExtra("user", element.getUsers());
                startActivity(intent);
            }
        });
        sortListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showDialog(sourceDataList.get(position).getUsers());
                return true;
            }
        });
        // 根据a-z进行排序源数据
        mClearEditText = findViewById(R.id.fr_filter_edit);
        mClearEditText.setVisibility(View.VISIBLE);
        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    /**
     * 弹出框进行常用联系人设置
     * @param user
     */
    private void showDialog(final MyUser user) {
        String content="是否设置为常用联系人？";
        new AlertDialog.Builder(mActivity)
                .setTitle("提示")
                .setMessage(content)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadingDialog.show();
                        MyUser newUser=MyUser.getCurrentUser(mActivity,MyUser.class);
                        if (newUser.getObjectId().equals(user.getObjectId())){
                            UIHelper.ToastMessage(mActivity,"不能设置自己为常用联系人");
                            loadingDialog.dismiss();
                            dialog.dismiss();
                            return;
                        }
                        BmobRelation newRelation=new BmobRelation();
                        newRelation.add(user);
                        newUser.setFrequentContacts(newRelation);
                        newUser.update(mActivity, newUser.getObjectId(), new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                loadingDialog.dismiss();
                                UIHelper.ToastMessage(mActivity,"添加常用联系人成功");
                                listener.frequentUserChanged();
                            }

                            @Override
                            public void onFailure(int i, String s) {

                                loadingDialog.dismiss();
                                UIHelper.ToastMessage(mActivity,"操作失败:"+s);
                            }
                        });
                    }
                })
                .show();

    }

    /**
     * 为ListView填充数据
     *
     * @return
     */
    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
        sourceDataList =new ArrayList<>();
        loadingDialog = new ProgressDialog(mActivity);
        loadingDialog.setMessage("加载中...");
        loadingDialog.show();

        BmobQuery<MyUser> query=new BmobQuery<>();
        query.findObjects(mActivity, new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                loadingDialog.dismiss();
                if (list == null || list.size() == 0) {
                    UIHelper.ToastMessage(mActivity, "无用户数据");
                } else {
                    for (MyUser user : list) {
                        SortModel sortModel = new SortModel();
                        sortModel.setUsers(user);
                        sortModel.setHeadUrl(user.getHeadPic());
                        //汉字转换成拼音
                        String pinyin = Pinyin4JUtil.getPinyinToLowerCase(user.getNick());
                        if (pinyin.contains(",")) {
                            pinyin = pinyin.split(",")[0];
                        }
                        String sortString = "";
                        if (null != pinyin && !"".equals(pinyin)) {
                            sortString = pinyin.substring(0, 1).toUpperCase();
                        }

                        // 正则表达式，判断首字母是否是英文字母
                        if (sortString.matches("[A-Z]")) {
                            sortModel.setSortLetters(sortString.toUpperCase());
                        } else {
                            sortModel.setSortLetters("#");
                        }
                        sourceDataList.add(sortModel);
                    }
                    Collections.sort(sourceDataList, pinyinComparator);
                    adapter = new SortAdapter(mActivity, sourceDataList);
                    sortListView.setAdapter(adapter);
                }
            }

            @Override
            public void onError(int i, String s) {
                loadingDialog.dismiss();
                UIHelper.ToastMessage(mActivity,"加载失败："+s);
            }
        });
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();
        if (sourceDataList != null) {
            if (TextUtils.isEmpty(filterStr)) {
                filterDateList = sourceDataList;
            } else {
                filterDateList.clear();
                for (SortModel sortModel : sourceDataList) {
                    String name = sortModel.getUsers().getNick();
                    String pinyin = Pinyin4JUtil.getPinyinToLowerCase(name);
                    if (pinyin.contains(",")) {
                        pinyin = pinyin.split(",")[0];
                    }
                    if (name.indexOf(filterStr.toString()) != -1 || pinyin.startsWith(filterStr.toString())
                            || sortModel.getUsers().getMobilePhoneNumber().contains(filterStr)) {
                        filterDateList.add(sortModel);
                    }
                }
            }

            // 根据a-z进行排序
            Collections.sort(filterDateList, pinyinComparator);
            adapter.updateListView(filterDateList);
        }
    }


    OnFrequentUserChanged listener;
    public void setOnFrequentUserChanged(OnFrequentUserChanged listener) {
        this.listener = listener;
    }
    public interface OnFrequentUserChanged {
        void frequentUserChanged();
    }
}
